<?php
namespace ZfcAdmin\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\View\Model\JsonModel;
use ScnSocialAuth\Mapper\UserProviderInterface;
use Users\Model\Admin;
use Users\Model\AdminTable;
use Users\Model\Usernew;
use Users\Model\USerTable;
use Users\Model\Usersnew;
use Users\Model\UsersnewTable;
use Products\Model\Productsnew;
use Products\Model\Categories;

use Zend\Session\Container;


class AdminController extends AbstractActionController
{
	protected  $adminTable;
	protected  $userTable;
	protected  $usersnewTable;
	protected  $categoriesTable;
	protected  $productsnewTable;
	
	
	public function indexAction()
	{
		if(isset($_POST['adminUsername']) && $_POST['adminUsername']!=""){
			$checkLogin = $this->getusersnewTable()->checkadminLogin($_POST);
			if($checkLogin!=""){
				$user_session = new Container('admin');
				$user_session->username=$checkLogin->company_name;
				$user_session->email=$checkLogin->email;
				$user_session->user_id=$checkLogin->user_id;
				$user_session->user_type=$checkLogin->user_type;
				$result = new JsonModel(array(					
						'output' 	=> 'success',
						'type'      => $checkLogin->user_type,
				));				
				return $result;					
			}else{
				$result = new JsonModel(array(					
					'output' 	=> 'notsuccess',
				));		
				return $result;				
			}			
		}else{
			return $view = new ViewModel(); 
		}
	}
	public function logoutAction()
	{
		unset($_SESSION['admin']);
		return $this->redirect()->toUrl('admin');
	}
	public function getAdminTable()
    {
        if (!$this->adminTable) {
            $sm = $this->getServiceLocator();
            $this->adminTable = $sm->get('Users\Model\AdminTable');			
        }
        return $this->adminTable;
    }
	public function changepasswordAction()
	{
		
	}
	public function allusersListAction()
	{
		if($_POST){
			$user_type=$_SESSION['admin']['user_type'];
			$userdata = $this->getusersnewTable()->getdataUsers($_POST['categories']);
			return new ViewModel(array(
				'data' 	=> $userdata,
				'type'	=> $_POST['categories'],
			));
		}
		if(isset($_SESSION['admin']) && $_SESSION['admin']['user_id']){
			$userdata = $this->getusersnewTable()->getdataUsers($_SESSION['admin']['user_type']);
			return new ViewModel(array(
				'data' 	=> $userdata,
				'type'  => '',
			));
		}
	}
	public function adminAllusersListAction()
	{
		if(isset($_SESSION['admin']) && $_SESSION['admin']['user_id']){
			$user_id=$_SESSION['admin']['user_id'];
			$userdata = $this->getusersnewTable()->getadminUsers($user_id);
			return new ViewModel(array(
				'data' 	=> $userdata,
				'type'  => '',
			));
		}
	}
	public function checkPasswordAction(){	
		$pwdExit = $this->getAdminTable()->getpassword($_POST['oldpasswrd'],$_POST['userId']);		
		if($pwdExit>0){			
			$result = new JsonModel(array(					
				'output' => 'success',
			));			
		}else{
			$result = new JsonModel(array(					
				'output' => 'not success',
			));
		}
		return $result;		
	}
	
	public function getUserTable(){
        if (!$this->userTable) {
            $sm = $this->getServiceLocator();
            $this->userTable = $sm->get('Users\Model\UserTable');
        }
        return $this->userTable;
    }
	public function getUniqueCode($length = "")
	{
		$code = md5(uniqid(rand(), true));
		if ($length != "")
		return substr($code, 0, $length);
		else
		return $code;
	}
	public function addUsersAction()
	{
		$request = $this->getRequest();
		if ($request->isPost()) {
			global $regSubject,$regMessage;	
			$password = $this->getUniqueCode('10');			
			$user_type=$this->getUserTable()->addUser($_POST,$password);	
			$userId=$user_type->user_id;
			$username=$user_type->username;
			$useremail=$user_type->email;			
			//Mailing				
			global $regSubject;				
			global $regMessage;
			$regMessage = str_replace("<FULLNAME>","$username", $regMessage);
			$regMessage = str_replace("<ACTIVATIONLINK>","http://" . $_SERVER['HTTP_HOST']."/users/reg-authentication?uid=".base64_encode($userId), $regMessage);	
			$to=$useremail;				
			include('public/PHPMailer_5.2.4/sendmail.php');				
			if(sendMail($to,$regSubject,$regMessage)){
				$result = new JsonModel(array(					
					'output' 		=> 'success',
					'success'		=>	true,
				));	
			}else{
				$result = new JsonModel(array(					
					'output' => 'not success',
					'not success'=>false,
				));	
			}
			return $result;
		}else{
			$table = $this->getServiceLocator()->get('Application\Model\countryTable');
			$getCountries=$table->getallcountries();
			$viewModel = new ViewModel();
			$viewModel->setVariable('countries', $getCountries);
			return $viewModel;
		}
	}
	public function addUserPreviousAction()
	{
		if(isset($_POST['cname']) && $_POST['cname']!=""){
				$user_session = new Container('adminusers');
				$user_session->cname=$_POST['cname'];
				$user_session->industry=$_POST['industry'];
				$user_session->address1=$_POST['address1'];
				$user_session->address2=$_POST['address2'];
				$user_session->address3=$_POST['address3'];
				$user_session->lmnear=$_POST['lmnear'];
				$user_session->city=$_POST['city'];
				$user_session->country=$_POST['country'];
				$user_session->email=$_POST['email'];
				$user_session->phone=$_POST['phone'];
				$user_session->fax=$_POST['fax'];
			if(isset($_POST['user']) && $_POST['user']!=''){
				$user_session->no=$_POST['user'];
				$get_user_id = $this->getusersnewTable()->updateUser1($_SESSION['adminusers']);
				return $this->redirect()->toUrl('add-user-next?user='.$_POST['user']);
			}else{
				return $this->redirect()->toUrl('add-user-next');
			}
		}
		if(isset($_GET['user']) && $_GET['user']!=''){
			$get_user_details = $this->getusersnewTable()->getUser($_GET['user']);
			$user_session = new Container('adminusers');
			$user_session->cname=$get_user_details->company_name;
			$user_session->industry=$get_user_details->industry;
			$user_session->address1=$get_user_details->address1;
			$user_session->address2=$get_user_details->address2;
			$user_session->address3=$get_user_details->address3;
			$user_session->lmnear=$get_user_details->landmarknearby;
			$user_session->city=$get_user_details->city;
			$user_session->country=$get_user_details->country;
			$user_session->email=$get_user_details->email;
			$user_session->phone=$get_user_details->phone;
			$user_session->fax=$get_user_details->fax;
			$user_session->parent_user_id=$get_user_details->parent_user_id;
			$user_session->password=$get_user_details->password;
			//new
			$user_session->cperson=$get_user_details->contact_person;
			$user_session->mobile=$get_user_details->mobile;
			$user_session->second_email=$get_user_details->second_email;
			$user_session->baddress=$get_user_details->bankaddress;
			$user_session->acno=$get_user_details->account_number;
			$user_session->note=$get_user_details->note;
			$user_session->type=$get_user_details->user_type;
		}
	   $table = $this->getServiceLocator()->get('Application\Model\countryTable');
	   $getCountries=$table->getallcountries();
	    return new ViewModel(array(
			'countries' 	=> $getCountries,				
	    ));
    }
	public function addUserNextAction()
	{
		include('public/PHPMailer_5.2.4/sendmail.php');
		if(isset($_POST['cperson']) && $_POST['cperson']!=""){
			$user_session = new Container('adminusers');
			$user_session->cperson=$_POST['cperson'];
			$user_session->mobile=$_POST['mobile'];
			$user_session->second_email=$_POST['email'];
			$user_session->baddress=$_POST['baddress'];
			$user_session->acno=$_POST['acno'];
			$user_session->note=$_POST['note'];
			$user_session->type=$_POST['type'];	
			$user_session->u_status=$_POST['u_status'];	
			$password = $this->getUniqueCode('10');
			if(isset($_POST['user']) && $_POST['user']!=''){
				$user_session->no=$_POST['user'];	
				$get_user_id = $this->getusersnewTable()->updateUser($_SESSION['adminusers']);
				unset($_SESSION['adminusers']);
				if($_SESSION['admin']['user_type']=='admin'){ 
						return $this->redirect()->toUrl('admin_allusers-list');
				}else if($_SESSION['admin']['user_type']=='superadmin'){
						return $this->redirect()->toUrl('allusers-list');
				}
			}else{
				$get_user_id = $this->getusersnewTable()->adduser($_SESSION['adminusers'],$password);
				if($get_user_id!=""){			
					unset($_SESSION['adminusers']);
					global $regSubject;				
					global $regMessage;
					$username=ucfirst($_SESSION['admin']['username']);
					$createEmailid=$get_user_id->email;
					$regMessage = str_replace("<FULLNAME>","$username", $regMessage);
					$regMessage = str_replace("<EMAIL>","$createEmailid", $regMessage);
					$regMessage = str_replace("<PASSWORD>","$password", $regMessage);
					if(sendMail($createEmailid,$regSubject,$regMessage)){
						$result = new JsonModel(array(					
							'output' 		=> 'success',
							'success'		=>	true,
						));	
					}
					if($_SESSION['admin']['user_type']=='admin'){ 
						return $this->redirect()->toUrl('admin_allusers-list');
					}else if($_SESSION['admin']['user_type']=='superadmin'){
						return $this->redirect()->toUrl('allusers-list');
					}
				}
			}			
		}
		if(isset($_GET['user']) && $_GET['user']!=''){
			$get_user_details = $this->getusersnewTable()->getUser($_GET['user']);
			$user_session = new Container('adminusers');
			$user_session->cperson=$get_user_details->contact_person;
			$user_session->mobile=$get_user_details->mobile;
			$user_session->second_email=$get_user_details->second_email;
			$user_session->baddress=$get_user_details->bankaddress;
			$user_session->acno=$get_user_details->account_number;
			$user_session->note=$get_user_details->note;
			$user_session->type=$get_user_details->user_type;
			$user_session->u_status=$get_user_details->u_status;
		}
	}
	public function deleteAction()
    {
		if(isset($_GET['user']) && $_GET['user']!=''){
			$get_user_details = $this->getusersnewTable()->getUserdelete($_GET['user']);
			if($_SESSION['admin']['user_type']=='admin'){ 
				return $this->redirect()->toUrl('admin_allusers-list');
			}else if($_SESSION['admin']['user_type']=='superadmin'){
				return $this->redirect()->toUrl('allusers-list');
			}
		}
    }
	public function viewUserAction()
    {
		if($_POST){
			if($_SESSION['admin']['user_type']=='admin'){ 
				return $this->redirect()->toUrl('admin_allusers-list');
			}else if($_SESSION['admin']['user_type']=='superadmin'){
				return $this->redirect()->toUrl('allusers-list');
			}
		}
		if(isset($_GET['user']) && $_GET['user']!=''){
			$get_user_details = $this->getusersnewTable()->getuserDetailes($_GET['user']);
			return new ViewModel(array(
				'data' 		=> $get_user_details->current(),
			));
		}
    }
	public function getusersnewTable()
    {
        if (!$this->usersnewTable) {
            $sm = $this->getServiceLocator();
            $this->usersnewTable = $sm->get('Users\Model\UsersnewTable');
        }
        return $this->usersnewTable;
    }
	public function productsListAction(){
		if(isset($_POST['catogoryValue']) && $_POST['catogoryValue']!=""){
			$paginator = $this->getProductsnewTable()->getallProducts2($_POST['catogoryValue']);
			$categories = $this->getCategoriesTable()->getallCategories();	
			return new ViewModel(array(
				'getallProducts'   	 => $paginator,
				'categories'  		 => $categories,
				'data'  			 => $_POST['catogoryValue'],
			));
		}else{
			$paginator = $this->getProductsnewTable()->getallProducts1(true);
			$categories = $this->getCategoriesTable()->getallCategories();
			return new ViewModel(array(
				'getallProducts'   	 => $paginator,
				'categories'  		 => $categories,
				'data'				 => '',
			));
		}
	}
	public function getCategoriesTable()
    {
        if (!$this->categoriesTable) {				
            $sm = $this->getServiceLocator();
            $this->categoriesTable = $sm->get('Products\Model\CategoriesTable');			
        }
        return $this->categoriesTable;
    }
	public function getProductsnewTable()
    {
        if (!$this->productsnewTable) {				
            $sm = $this->getServiceLocator();
            $this->productsnewTable = $sm->get('Products\Model\ProductsnewTable');			
        }
        return $this->productsnewTable;
    }
	public function addProductNextAction(){		
		if(isset($_POST['hid_product_id']) && $_POST['hid_product_id']=="" && $_POST['qty']!=''){
			$user_session = new Container('products');
			$user_session->qty=$_POST['qty'];
			$user_session->units=$_POST['units'];
			$user_session->year=$_POST['year'];
			$user_session->packing=$_POST['packing'];
			$user_session->per=$_POST['per'];
			$user_session->tsh=$_POST['tsh'];
			$user_session->tshm=$_POST['tshm'];
			$get_product_id = $this->getProductsnewTable()->addProducts($_SESSION['products']);
			if($get_product_id!=""){			
				unset($_SESSION['products']);
				return $this->redirect()->toUrl('/admin/products-list');
			}	
		}else if(isset($_POST['hid_product_id']) && $_POST['hid_product_id']!="" && $_POST['qty']!=""){
			$user_session = new Container('products');
			$user_session->qty=$_POST['qty'];
			$user_session->units=$_POST['units'];
			$user_session->year=$_POST['year'];
			$user_session->packing=$_POST['packing'];
			$user_session->per=$_POST['per'];
			$user_session->tsh=$_POST['tsh'];
			$user_session->tshm=$_POST['tshm'];
			$productid=$_POST['hid_product_id'];			
			$get_product_id = $this->getProductsnewTable()->updateProducts($_SESSION['products'],$productid);			
			if($get_product_id>=0){
				unset($_SESSION['products']);
				return $this->redirect()->toUrl('/admin/products-list');
			}			
		}else if(isset($_GET['product_id']) && $_GET['product_id']!=""){
			$countrytable = $this->getServiceLocator()->get('Application\Model\countryTable');
			$getCountries=$countrytable->getallcountries();
			$getallcategories = $this->getCategoriesTable()->getallCategories();
			$get_product_details = $this->getProductsnewTable()->getProducts($_GET['product_id']);
			return new ViewModel(array(
				'productsDeatils'   =>  $get_product_details,
				'getCountries'      =>  $getCountries,
				'getallcategories'  =>  $getallcategories,
			));
		}
	}	
	public function addProductAction(){	
		if(isset($_POST['hid_product_id']) && $_POST['hid_product_id']=="" && $_POST['brand']!=""){
			$user_session = new Container('products');
			$user_session->brand=$_POST['brand'];
			$user_session->generic=$_POST['generic'];
			$user_session->fuction=$_POST['fuction'];
			$user_session->manufacture=$_POST['manufacture'];
			$user_session->origin=$_POST['origin'];
			$user_session->category_id=$_POST['category_id'];
			if(isset($_POST['hid_product_id']) && $_POST['hid_product_id']!=""){
				$product_id=$_POST['hid_product_id'];
				return $this->redirect()->toUrl('/admin/add-product-next?product_id='.$product_id);
			}else{
				return $this->redirect()->toUrl('/admin/add-product-next');
			}				
		}else if(isset($_POST['hid_product_id']) && $_POST['hid_product_id']!="" && $_POST['brand']!=""){	
			$user_session = new Container('products');
			$user_session->brand=$_POST['brand'];
			$user_session->generic=$_POST['generic'];
			$user_session->fuction=$_POST['fuction'];
			$user_session->manufacture=$_POST['manufacture'];
			$user_session->origin=$_POST['origin'];
			$user_session->category_id=$_POST['category_id'];
			if(isset($_POST['hid_product_id']) && $_POST['hid_product_id']!=""){
				$product_id=$_POST['hid_product_id'];
				return $this->redirect()->toUrl('/admin/add-product-next?product_id='.$product_id);
			}else{
				return $this->redirect()->toUrl('/admin/add-product-next');
			}
		}else if(isset($_GET['product_id']) && $_GET['product_id']!=""){
			$countrytable = $this->getServiceLocator()->get('Application\Model\countryTable');
			$getCountries=$countrytable->getallcountries();
			$getallcategories = $this->getCategoriesTable()->getallCategories();
			$get_product_details = $this->getProductsnewTable()->getProducts($_GET['product_id']);
			return new ViewModel(array(
				'productsDeatils'    =>  $get_product_details,
				'getCountries'    =>  $getCountries,
				'getallcategories'    =>  $getallcategories,
			));
		}else{			
		    $countrytable = $this->getServiceLocator()->get('Application\Model\countryTable');
			$getCountries=$countrytable->getallcountries();
			$getallcategories = $this->getCategoriesTable()->getallCategories();
			return new ViewModel(array(
				'getCountries'    =>  $getCountries,
				'getallcategories'    =>  $getallcategories,
			));
		}
	}
}